<template>
  <div class="mb-[0.5rem]" v-if="search">
    <a-input
      v-model:value.trim="searchValue"
      :placeholder="searchPlaceholder"
      v-filter-special-chars
    >
      <template #suffix>
        <SearchOutlined class="ml-2 cursor-pointer" />
      </template>
    </a-input>
  </div>
  <a-spin :spinning="loading">
    <a-tree
      v-if="filteredTreeData?.length"
      v-model:selectedKeys="selectedKeys"
      :blockNode="true"
      :disabled="disabled"
      :tree-data="filteredTreeData"
      :defaultExpandAll="true"
      :autoExpandParent="true"
      :fieldNames="{ children: 'children', title: 'name', key: 'id' }"
      @select="handleSelect"
    >
      <template #title="{ name }">
        <div class="ellipsis-label" :title="name">
          {{ name }}
        </div>
      </template>
    </a-tree>
    <a-empty v-else :image="simpleImage" />
  </a-spin>
</template>

<script setup lang="ts">
import { onBeforeMount, ref, computed } from 'vue'
import { Empty } from 'ant-design-vue'
import type { TreeProps } from 'ant-design-vue'
import { SearchOutlined } from '@ant-design/icons-vue'

import { getDeviceTree } from '@/api/organization'

const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE

const emit = defineEmits(['updateCurrent', 'updateRootId', 'updateRootName'])

defineProps({
  search: {
    type: Boolean,
    default: true
  },
  searchPlaceholder: {
    type: String,
    default: '请输入'
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const treeData = ref<TreeProps['treeData']>([]) // 树数据
const selectedKeys = ref<string[] | number[]>([]) // 选中的key

const loading = ref(false)
const rootId = ref()
const rootItem = ref()

// 顶部搜索框
const searchValue = ref('')
// 根据输入框内容对节点进行过滤,需要过滤树型数据,输入内容后只显示站点
const filteredTreeData = computed(() => {
  if (searchValue.value) {
    return filterTreeData(treeData.value)
  } else {
    return treeData.value
  }
})

console.log(filteredTreeData.value, '===filteredTreeData')

const filterTreeData = (data: TreeProps['treeData']): any => {
  if (!data) return
  return data
    .map((node) => {
      // console.log(node.name, 'node')
      if (node.name.includes(searchValue.value)) {
        if (node.children) {
          return {
            ...node,
            children: filterTreeData(node.children)
          }
        } else {
          return node
        }
      } else {
        if (node.children) {
          const filteredChildren = filterTreeData(node.children)
          if (filteredChildren.length > 0) {
            return {
              ...node,
              children: filteredChildren
            }
          }
        }
      }
      return null
    })
    .filter((node) => node !== null)
}

// 获取树型结构站点树
const initTreeFun = async () => {
  loading.value = true
  getDeviceTree()
    .then((res) => {
      console.log(res, '树型结构站点')

      rootId.value = res[0].id
      rootItem.value = res[0]
      emit('updateRootId', res[0].id)
      emit('updateRootName', res[0].name)

      treeData.value = res
      emit('updateCurrent', res[0])

      loading.value = false
    })
    .catch(() => {
      treeData.value = []
      loading.value = false
    })
}

// 选中节点
const currentNode = ref()
const handleSelect = (
  _selectedKeys: any,
  e: { selected: boolean; selectedNodes: any }
) => {
  if (e.selectedNodes[0] === undefined) {
    currentNode.value = rootItem.value
  } else {
    currentNode.value = e.selectedNodes[0]
  }
  console.log('======选中树节点======', currentNode.value)
  emit('updateCurrent', currentNode.value)
}

const setSelectedKeys = (value: string[] | number[]) => {
  selectedKeys.value = value
  if (value.length === 0 && treeData.value && treeData.value.length > 0) {
    rootId.value = treeData.value[0].id
    emit('updateRootId', treeData.value[0].id)
    emit('updateRootName', treeData.value[0].name)
    emit('updateCurrent', treeData.value[0])
  }
}

onBeforeMount(() => {
  initTreeFun()
})

defineExpose({ rootId, setSelectedKeys, initTreeFun })
</script>

<style lang="less">
.ant-input-suffix {
  color: @placeholder-text-color;
}

.ant-spin-spinning {
  display: flex;
  justify-content: center;
  align-items: center;
}

.ant-spin-nested-loading,
.ant-spin-spinning {
  height: calc(100% - 4.75rem);

  .ant-spin-container {
    height: 100%;

    .ant-tree {
      overflow-y: auto;
      height: 100%;
    }
  }
}

.ellipsis-label {
  overflow: hidden;
  width: 13em;
  text-overflow: ellipsis;
  white-space: nowrap;
  word-break: break-all;
}

.ant-tree-indent-unit {
  width: 1rem;
}
</style>
